/*
 * @Description:月饼
 * @Author: YoungWind
 * @Date: 2020-09-29 10:40:45
 * @LastEditTime: 2020-10-08 20:02:13
 * @LastEditors: YoungWind
 * @FilePath: \ccd3\src\ccd3\flower\charts\Flowers.js
 */
import BaseChart from '../../BaseChart.js'
export default class Flowers extends BaseChart {
	constructor(id, data) {
		super(id, data)
		this.color = d3.schemeCategory10 //

		this.flowersNum = 10
		this.petalsNum = 5
		this.factor = 1

		this.flowerRadius = 15
		this.flowerWidth = 10
		this.flowerAngle = Math.PI * 2

		this.duration = 1000
		this.delay = 1000
	}

	setFlowersNum(val) {
		this.flowersNum = val
		return this
	}
	setPetalsNum(val) {
		this.petalsNum = val
		return this
	}
	setFactor(val) {
		this.factor = val
		return this
	}
	setFlowerRadius(val) {
		this.flowerRadius = val
		return this
	}
	setFlowerWidth(val) {
		this.flowerWidth = val
		return this
	}
	setFlowerAngle(val) {
		this.flowerAngle = val
		return this
	}
	setDuration(val) {
		this.duration = val
		return this
	}
	setDelay(val) {
		this.delay = val
		return this
	}

	init() {
		this.initSvg()
		this.initMainGroup()
		this.initMoonGroup()
		return this
	}

	initMoonGroup() {
		this.petalGroup = this.mg.append('g')
	}

	render() {
		this.renderData()
		this.renderScale()
		this.renderPetal()
		return this
	}

	renderData() {
		let flowersNum = this.flowersNum
		let flowerRadius = this.flowerRadius
		let flowerWidth = this.flowerWidth
		this.data = []
		for (let i = 0; i < flowersNum; i++) {
			let len = flowerRadius
			let n = this.petalsNum
			this.data.push({
				center: [Math.random() * this.innerWidth, Math.random() * this.innerHeight],
				n: n,
				length: len,
				width: flowerWidth,
			})
		}
	}

	renderScale() {
		this.colorScale = d3.scaleOrdinal(this.color)
	}

	renderPetal() {
		this.petalGroups = this.petalGroup
			.selectAll('g')
			.data(this.data)
			.join('g')
			.attr('fill', (d, i) => this.colorScale(i))
			.attr('transform', (d) => `translate(${d.center[0]},${d.center[1]})`)

		this.petalElements = this.petalGroups
			.selectAll('path')
			.data((d, i) => {
				let p = []
				for (let j = 0; j < d.n; j++) {
					p.push({ iflower: i, angle: (j * Math.PI * 2) / d.n, length: d.length, width: d.width })
				}
				return p
			})
			.join('path')
			.transition()
			.delay((d) => d.iflower * this.delay)
			.transition()
			.duration(this.duration)
			.attrTween('d', (d) => {
				return (t) => {
					return this.petal(t * d.angle, t * d.length, t * d.width)
				}
			})
	}

	petal = (angle, length, width) => {
		let [dx, dy] = [Math.cos(angle), Math.sin(angle)]
		let [nx, ny] = [-Math.sin(angle), Math.cos(angle)]
		let s = this.factor
		return `M 0 0 
          Q ${dx * length * s + (nx * width) / 2} ${dy * length * s + (ny * width) / 2} ${
			dx * length
		} ${dy * length}
          Q ${dx * length * s - (nx * width) / 2} ${dy * length * s - (ny * width) / 2} 0 0 Z`
	}
}
